package sk.uniza.fri.cerviix.client.network.message.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import com.sun.jmx.remote.internal.ArrayQueue;

import sk.uniza.fri.cerviix.client.Game;
import sk.uniza.fri.cerviix.client.game.Player;
import sk.uniza.fri.cerviix.client.game.WormPart;
import sk.uniza.fri.cerviix.client.game.WormPart.Align;
import sk.uniza.fri.cerviix.client.network.ServerMessage;

public class UpdateMessage extends ServerMessage
{
	private Queue<PlayerStruct> players = new LinkedList<PlayerStruct>();
	
	@Override
	public void receive() throws IOException
	{
		int count = stream.readInt();
		
		for (int i = 0; i < count; i++)
		{
			int id, score;
			boolean alive;
			float x = 0.0f, y = 0.0f;
			
			id = stream.readInt();
			score = stream.readInt();
			alive = stream.readBoolean();
			
			if (alive)
			{
				x = stream.readFloat();
				y = stream.readFloat();
			}
			
			players.add(new PlayerStruct(id, score, alive, x, y));
		}
	}
	
	public static class PlayerStruct
	{
		public final int id;
		public final int score;
		public final boolean alive;
		public final float x, y;
		
		public PlayerStruct(int id, int score, boolean alive, float x, float y)
		{
			this.id = id;
			this.score = score;
			this.alive = alive;
			this.x = x;
			this.y = y;
		}
	}
	
	public void run(Game game)
	{
		while (!players.isEmpty())
		{
			PlayerStruct struct = players.remove();
			
			Player player = game.getPlayers().get(struct.id);
			
			if (player != null)
			{
				player.setScore(struct.score);
			}
			
			if (struct.alive)
			{
				Align align = (struct.id == game.getPlayerId()) ? Align.PLAYER : Align.ENEMY;
				
				game.addWormPart(new WormPart(align, struct.x, struct.y));
			}
			else
			{				
				if (player != null)
				{
					player.died();
				}
			}
		}
	}
}
